﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

using Microsoft.WindowsAzure.StorageClient;

namespace BizTalkFactory.Adapters.AzureStorage
{
    sealed class BlobStorageEventArgs : StorageEventArgs
    {
        public CloudBlob Blob;
        
        public BlobStorageEventArgs(string blobName, CloudBlob blob)
            : base(blobName) 
        {
            Blob = blob;
        }
    }

    class BlobStorageListener : StorageListener
    {
        private String containerName_ = string.Empty;

        public BlobStorageListener(AzureStorageAdapterConnection connection)
            : base(connection)
        {
        }

        #region Attributes

        public String ContainerName
        {
            get
            {
                return containerName_;
            }
            set
            {
                containerName_ = value;
            }
        }

        #endregion

        #region Overrides

        protected override void StartingListener()
        {
            base.StartingListener();
        }

        protected override void Listening()
        {
            string blobmask = Connection.ConnectionFactory.Adapter.BlobMask;
            
            CloudBlobContainer container = Connection.BlobStorage.GetContainerReference(containerName_);
           
            BlobRequestOptions options = new BlobRequestOptions();
            options.BlobListingDetails = BlobListingDetails.None;
            
            IEnumerable<IListBlobItem> blobList = container.ListBlobs(options);
            foreach (IListBlobItem item in blobList)
            {
                string blobPath = item.Uri.AbsoluteUri.Replace(item.Container.Uri.AbsoluteUri+"/", "");

                if (MatchMask(blobPath, blobmask))
                {
                    CloudBlob blob = container.GetBlobReference(blobPath);
                    BlobStorageEventArgs e = new BlobStorageEventArgs(containerName_, blob);
                    
                    RaiseReceivedEvent(this, e);

                    if (!e.Cancel)
                        blob.Delete();
                }
            }


            base.Listening();
        }

        private static bool MatchMask(string blobPath, string blobmask)
        {
            string pattern = String.Format("^{0}$",
                blobmask
                    .Replace(".", "\\.")
                    .Replace("?", ".")
                    .Replace("*", ".*")
                    );

            Regex regex = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);

            return regex.Match(blobPath).Success;
        }

        protected override void StoppingListener()
        {
            base.StoppingListener();
        }

        #endregion
    }
}
